var prefix = jsctx + "/enterprise/gain/setting";

var enterpriseGain = (function () {
    $('#exampleTable').on('load-success.bs.table', function (e, data) {
        if (data.total && !data.rows.length) {
            $('#exampleTable').bootstrapTable('selectPage').bootstrapTable('refresh');
        }
    });

    function reLoad() {
        $('#exampleTable').bootstrapTable('refresh');
        load();
    };

    function init() {
        setTimeout(function () {//防止先于-读取缓存执行
            load();
        }, 10)
    };
    var h = $(window).height() - 80;

    function load() {
        $('#exampleTable')
            .bootstrapTable({
                method: 'get',
                url: prefix + "/listPageGainSetting",
                iconSize: 'outline',
                toolbar: '#exampleToolbar',
                striped: false,
                dataType: "json",
                pagination: true,
                singleSelect: false,
                pageList: [10, 20, 30],
                pageSize: 10,
                pageNumber: 1,
                sidePagination: "server",
                cache: false,
                height: h,
                paginationShowPageGo: true,
                rightFixedColumns: false,
                queryParams: function (params) {
                    return {
                        pageNo: (params.offset / params.limit) + 1,
                        pageSize: params.limit,
                        gainName: $("#gainName").val(),
                    };
                },
                columns: [
                    {
                        field: 'number',
                        title: '序号',
                        width: '100', align: 'center',
                        formatter: function (value, row, index) {
                            return index + 1;
                        }
                    },
                    {field: 'enterpriseLevel', title: '企业等级', align: 'center'},
                    {field: 'gainName', title: '权益名称', align: 'center'},
                    {
                        field: 'gainLogo', title: '图标', align: 'center',
                        formatter: function (value, row, index) {
                            return "<img src=" + value + " width='50px' height='50px'>";
                        }
                    },
                    {field: 'gainExplain', title: '权益说明', align: 'center'},
                    {

                        field: 'status', title: '状态', width: '100', align: 'center',
                        formatter: function (value, row, index) {

                            if (value == '0') {
                                return  '<input class="tgl tgl-skewed" onclick="enterpriseGain.onSwitchChange(' + row.enterpriseGainId +',1 )" id="cb'+row.enterpriseGainId+'" type="checkbox"><label class="tgl-btn" data-tg-off="启动" data-tg-on="禁用" for="cb'+row.enterpriseGainId+'"></label>'
                            } else {
                                return '<input class="tgl tgl-skeweds"  onclick="enterpriseGain.onSwitchChange(' + row.enterpriseGainId +',0 )" id="cb'+row.enterpriseGainId+'" type="checkbox"> <label class="tgl-btn isok" data-tg-off="禁用" data-tg-on="启动" for="cb'+row.enterpriseGainId+'"></label>'
                            }
                        }
                    },
                    {
                        field: 'gainType', title: '权益类型', align: 'center',
                        formatter: function (value, row, index) {
                            if (value == '0') {
                                return "充值消费折扣";
                            } else {
                                return "尊享标识";
                            }
                        }

                    },
                    {field: 'sort', title: '排序', align: 'center'},
                    {
                        title: '操作',
                        field: 'orderId',
                        width: '200', align: 'center',
                        formatter: function (value, row, index) {
                            var a = '<a class="btn btn-primary btn-sm ' + has_edit + '" href="#" mce_href="#" title="编辑" onclick="enterpriseGain.editEnterpriseGain(\''
                                + row.enterpriseGainId + '\')">编辑</a> ';

                            var d = '<a class="btn btn-danger btn-sm ' + has_edit + '" href="#" mce_href="#" title="删除" onclick="enterpriseGain.deleteEnterpriseGain(\''
                                + row.enterpriseGainId + '\')">删除</a> ';

                            return a + d;
                        }
                    }
                ], onLoadSuccess: function () {

                }, onPageChange: function () {

                }
            });
    };
    /**
     * 导出列表
     */
    function exportList() {
        $.fileDownload(prefix + "/export", { // 后台请求链接
            httpMethod: "get",　　　　　　　　// 请求方式
            contentType: 'application/json',　 // 请求头
            data: {　　　　　　　　　　　　　　　// 参数，左边为后台接收的参数名，右边为前端获取的值，
                gainName: $('#gainName').val().trim(),
                offset: $('.active .page-link').text(),
                limit: $(".page-size").text()
            },
            prepareCallback: function (url) {
                layer.msg("文件下载中...", {time: -1})
            },
            abortCallback: function (url) {
                // 异常终止
                layer.msg("文件下载异常！！");
            },
            successCallback: function (url) {
                layer.msg("文件下载成功！！", {time: 1500});
            },
            failCallback: function (data) {
                var str = "{" + data.substring(data.indexOf("{") + 1, data.indexOf("}")) + "}";
                layer.msg(JSON.parse(str).message);
            }
        })
    }

    function onSwitchChange (isId, state) {
        //修改操作
        $.ajax({
            type: "post",
            dataType: "json",
            async: false,
            url: prefix + "/updateGainSettingStatus",
            data: {
                status: state ,
                id: isId
            },
            success: function (data) {
                reLoad();
            },
            error: function (xhr, error, exception) {
                let errorMsg = xhr.responseText;
                openMsg("error", "系统异常，" + errorMsg + "，请联系管理员！");
            }
        });
    }


    function addEnterpriseGain() {
        location.href = prefix + "/add";
    }

    function editEnterpriseGain(id) {
        location.href = prefix + "/edit/" + id;
    }


    function deleteEnterpriseGain(id) {
        layer.confirm('确定要删除选中的记录？', {
            btn: ['确定', '取消']
        }, function (index) {
            $.ajax({
                url: prefix + "/deleteEnterprisGain",
                type: "post",
                data: {
                    'id': id
                },
                success: function (data) {
                    layer.close(index);
                    if (data.status == 200) {
                        layer.msg("成功");
                        reLoad();
                    } else {
                        layer.msg(data.message);
                    }
                },
                error: function (xhr, error, exception) {
                    let errorMsg = xhr.responseText;
                    openMsg("error", "系统异常，" + errorMsg + "，请联系管理员！");
                }
            });
        })

    }

    return {
        init: init,
        reLoad: reLoad,
        editEnterpriseGain: editEnterpriseGain,
        deleteEnterpriseGain: deleteEnterpriseGain,
        exportList: exportList,
        onSwitchChange:onSwitchChange,
        addEnterpriseGain: addEnterpriseGain

    };
})();

var addEnterpriseGain = (function () {

    function init() {
        validateRule();
        load();

    };

    function load() {
        $('#subtable')
            .bootstrapTable({
                method: 'get',
                url: prefix + "/listPageEntGainGrade",
                iconSize: 'outline',
                toolbar: '#exampleToolbar',
                striped: false,
                dataType: "json",
                pagination: false,
                singleSelect: false,
                cache: false,
                paginationShowPageGo: true,
                rightFixedColumns: false,
                queryParams: function (params) {
                    return {
                        pageNo: 1,
                        pageSize: 100,
                        enterpriseGainId: -1,
                    };
                },
                columns: [
                    {
                        field: 'ids',
                        title: '序号',
                        width: '100', align: 'center',
                        formatter: function (value, row, index) {
                            return index + 1;
                        }
                    },
                    {field: 'rechargeAmount', title: '充值金额', align: 'center'},
                    {field: 'discountAmount', title: '消费折扣', align: 'center'},
                ], onLoadSuccess: function (data) {
                    var allTableData = $('#subtable').bootstrapTable('getData');
                    if (data.total === 0 && allTableData.length > 0) {
                    }
                }, onClickCell: function (field, value, row, $element) {
                    $element.attr('contenteditable', true);
                    //元素失去焦点事件
                    $element.blur(function () {

                        //单元格修改后的的值
                        let tdValue = $element.html();
                        let index = $element.parent().data('index');

                        //updateCell更新某单元格数据
                        $("#subtable").bootstrapTable('updateCell', {
                            index: index,       //行索引
                            field: field,       //列名
                            value: tdValue        //cell值
                        });
                    });
                }

            });
    };


    function addRow() {
        var length = $('#subtable').bootstrapTable('getData').length;

        //更新表格中的数据，否则点击添加后，填写的内容会被清空
        var params = new Array();
        for (var dataIndex = 0; dataIndex <= length; dataIndex++) {
            var columns = $('#subtable tr[data-index="' + dataIndex + '"] td');
            var obj = new Object();
            for (var i = 0; i < columns.length; i++) {
                var td = $(columns[i]);
                var key = td.attr('field');
                obj[key] = td.val();
            }
            params.push({index: dataIndex, row: obj});
        }

        // //更新行数据
        $('#subtable').bootstrapTable('updateRow', params);
        // //定位到最后一行
        $('#subtable').bootstrapTable('scrollTo', 'bottom');
        //
        $('#subtable').bootstrapTable('insertRow', {
            index: length,
            row: {
                "rechargeAmount": "",
                "discountAmount": ""
            }
        })
    }

    function save() {
        var imageFile=document.getElementById("file1").files[0];//IE10以下不支持
        if(imageFile){
            var imageData = new FormData(); //创建一个formData
            imageData.append('file', imageFile);
            $.ajax({
                cache: true,
                type: "POST",
                url: prefix + "/uploadImage",
                data: imageData,
                processData: false,
                contentType: false,
                async: false,
                error: function (request) {
                    parent.layer.alert("操作失败");
                },
                success: function (data) {
                    if (data.status == 200) {
                        console.log(data.data);
                        $("#gainLogo").val(data.data);
                    } else {
                        if (data.status == 600) {
                            javascript:history.back(-1);
                        } else {
                            parent.layer.alert(data.message);
                        }
                    }
                }
            });
        }
        // var formData = new FormData($("#frm")[0]);
        // var data = $('#subtable').bootstrapTable('getData');
        var formS = $('#frm').serializeObject();
        var rechargeAmountArr = formS.rechargeAmount;
        var discountAmountArr = formS.discountAmount;
        var data = [];
        if (rechargeAmountArr != undefined && rechargeAmountArr != null) {
            for(var j=0;j<rechargeAmountArr.length;j++){
                var obj = {};
                obj.rechargeAmount = rechargeAmountArr[j];
                obj.discountAmount = discountAmountArr[j];
                data.push(obj)
            }
        }
        delete formS.rechargeAmount
        delete formS.discountAmount
        $.ajax({
            cache: false,
            type: "POST",
            dataType: "json",
            headers:{
                'Content-Type':'application/json;charset=UTF-8',
            },
            processData: false, //add this
            contentType: false, //and this

            url: prefix + "/addEntGainSetting",
            data: JSON.stringify({
                "gainSetting":formS,
                "gradeList":data
            }),
            error: function (request) {
                parent.layer.alert("操作失败");
            },
            success: function (data) {
                if (data.status == 200) {
                    parent.layer.msg("成功");
                    javascript:history.back(-1);
                } else {
                    if (data.status == 600) {
                        javascript:history.back(-1);
                    } else {
                        parent.layer.alert(data.message);
                    }
                }
            }
        });
    };



    function validateRule() {
        var icon = "<i class='fa fa-times-circle'></i> ";
        $("#frm").validate({
            rules: {
                enterpriseLevel: {
                    required: true
                },
                gainName: {
                    required: true
                }
            },
            messages: {
                enterpriseLevel: {
                    required: icon + "请选择权益等级"
                },gainName: {
                    required: icon + "请输入权益名称"
                }
            },
            submitHandler: function (form) {
                save();
            }
        })
    };

    $.fn.serializeObject = function() {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function() {
            if (o[this.name] !== undefined) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };

    return {
        init: init,
        addRow: addRow
    };


})();

var editEnterpriseGain = (function () {
    var delGainList = new Array();

    function init() {

        validateRule();
        load();
    };

    function load() {
        $('#subtable')
            .bootstrapTable({
                method: 'get',
                url: prefix + "/listPageEntGainGrade",
                iconSize: 'outline',
                toolbar: '#exampleToolbar',
                striped: false,
                dataType: "json",
                pagination: false,
                singleSelect: false,
                cache: false,
                paginationShowPageGo: true,
                rightFixedColumns: false,
                queryParams: function (params) {
                    return {
                        pageNo: 1,
                        pageSize: 100,
                        enterpriseGainId: $("#enterpriseGainId").val(),
                    };
                },
                columns: [
                    {
                        field: 'index',
                        title: '序号',
                        width: '100', align: 'center',
                        formatter: function (value, row, index) {
                            return index + 1;
                        }
                    },
                    {field: 'gainGradeId', title: '', align: 'center', visible:false},
                    {field: 'rechargeAmount', title: '充值金额', align: 'center'},
                    {field: 'discountAmount', title: '消费折扣', align: 'center'},
                    {
                        title: '操作',
                        field: '',
                        width: '200', align: 'center',
                        formatter: function (value, row, index) {
                            var deleteIndex = index;
                            var d = '<a class="btn btn-primary btn-sm" href="#" title="删除" onclick="editEnterpriseGain.removeRow(\''
                                + row.gainGradeId + '\','+ deleteIndex +')">删除</a> ';

                            return d;
                        }
                    }
                ], onLoadSuccess: function (data) {
                    var allTableData = $('#subtable').bootstrapTable('getData');
                    if (data.total === 0 && allTableData.length > 0) {
                    }
                }, onClickCell: function (field, value, row, $element) {
                    $element.attr('contenteditable', true);
                    //元素失去焦点事件
                    $element.blur(function () {

                        //单元格修改后的的值
                        let tdValue = $element.html();
                        let index = $element.parent().data('index');

                        //updateCell更新某单元格数据
                        $("#subtable").bootstrapTable('updateCell', {
                            index: index,       //行索引
                            field: field,       //列名
                            value: tdValue        //cell值
                        });
                    });
                }

            });
    };


    function addRow() {
        var length = $('#subtable').bootstrapTable('getData').length;

        //更新表格中的数据，否则点击添加后，填写的内容会被清空
        var params = new Array();
        for (var dataIndex = 0; dataIndex <= length; dataIndex++) {
            var columns = $('#subtable tr[data-index="' + dataIndex + '"] td');
            var obj = new Object();
            for (var i = 0; i < columns.length; i++) {
                var td = $(columns[i]);
                var key = td.attr('field');
                obj[key] = td.val();
            }
            params.push({index: dataIndex, row: obj});
        }

        // //更新行数据
        $('#subtable').bootstrapTable('updateRow', params);
        // //定位到最后一行
        $('#subtable').bootstrapTable('scrollTo', 'bottom');
        //
        $('#subtable').bootstrapTable('insertRow', {
            index: length,
            row: {
                "rechargeAmount": "",
                "discountAmount": ""
            }
        })
    }

    function save() {
        var imageFile=document.getElementById("file1").files[0];//IE10以下不支持
        if(imageFile){
            var imageData = new FormData(); //创建一个formData
            imageData.append('file', imageFile);
            $.ajax({
                cache: true,
                type: "POST",
                url: prefix + "/uploadImage",
                data: imageData,
                processData: false,
                contentType: false,
                async: false,
                error: function (request) {
                    parent.layer.alert("操作失败");
                },
                success: function (data) {
                    if (data.status == 200) {
                        console.log(data.data);
                        if (data.data != null && data.data != '') {
                            $("#gainLogo").val(data.data);
                        }
                    } else {
                        parent.layer.alert(data.message);
                    }
                }
            });
        }
        // var data = $('#subtable').bootstrapTable('getData');
        var formS = $('#frm').serializeObject();
        var gainGradeIdArr = formS.gainGradeId;
        var rechargeAmountArr = formS.rechargeAmount;
        var discountAmountArr = formS.discountAmount;
        var data = [];
        if (gainGradeIdArr != undefined && gainGradeIdArr != null) {
            for(var j=0;j<gainGradeIdArr.length;j++){
                var obj = {};
                obj.gainGradeId = gainGradeIdArr[j];
                obj.enterpriseGainId = formS.enterpriseGainId;
                obj.rechargeAmount = rechargeAmountArr[j];
                obj.discountAmount = discountAmountArr[j];
                data.push(obj)
            }
        }

        delete formS.gainGradeId
        delete formS.rechargeAmount
        delete formS.discountAmount
        $.ajax({
            cache: false,
            type: "POST",
            dataType: "json",
            headers:{
                'Content-Type':'application/json;charset=UTF-8',
            },

            url: prefix + "/updateEntGainSetting",
            data:JSON.stringify({
                "gainSetting":formS,
                "gradeList":data,
                "delGradeList":delGainList
            }),
            error: function (request) {
                parent.layer.alert("操作失败");
            },
            success: function (data) {
                if (data.status == 200) {
                    parent.layer.msg("成功");
                    javascript:history.back(-1);
                } else {
                    if (data.status == 600) {
                        javascript:history.back(-1);
                    } else {
                        parent.layer.alert(data.message);
                    }
                }
            }
        });
    };

    function removeRow(id, index){
        if (typeof(id) != undefined && id != 'undefined') {
            delGainList.push(id);
        }


        $('#subtable').bootstrapTable('remove', {
            field: '$index',
            values: [index]
        });
    }

    function validateRule() {
        var icon = "<i class='fa fa-times-circle'></i> ";
        $("#frm").validate({
            rules: {
                enterpriseLevel: {
                    required: true
                },
                gainName: {
                    required: true
                }
            },
            messages: {
                enterpriseLevel: {
                    required: icon + "请选择权益等级"
                },gainName: {
                    required: icon + "请输入权益名称"
                }
            },
            submitHandler: function (form) {
                save();
            }
        })
    };


    return {
        init: init,
        addRow: addRow,
        removeRow:removeRow
    };


})();
